﻿using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.SessionState;
using System.Web.Caching;
using System.Threading;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;

namespace CNVP.Framework
{
    public class BasePage
    {
        #region MessageBoxUp用来在客户端弹出对话框,刷新上级页面
        /// <summary>
        /// 说明：MessageBox用来在客户端弹出对话框。
        /// 参数：TxtMessage 对话框中显示的内容。
        /// </summary>
        public static void MessageBoxUp(string TxtMessage)
        {
            string str;
            str = "<script language=javascript>alert('" + TxtMessage + "');parent.ColumnLeft.location.reload();</script>";
            HttpContext.Current.Response.Write(str);
        }
        #endregion

        #region MessageBox用来在客户端弹出对话框。
        /// <summary>
        /// 说明：MessageBox用来在客户端弹出对话框。
        /// 参数：TxtMessage 对话框中显示的内容。
        /// </summary>
        public static void MessageBox(string TxtMessage)
        {
            string str;
            str = @"<script type='text/javascript'>alert('" + TxtMessage + @"');</script>";
            HttpContext.Current.Response.Write(str);
        }
        /// <summary>
        /// 说明：MessageBox用来在客户端弹出对话框，返回历史页面。
        /// 参数：TxtMessage 对话框中显示的内容。
        /// </summary>
        public static void MessageBoxGoHistory(string TxtMessage)
        {
            string str;
            str = @"<script type='text/javascript'>alert('" + TxtMessage + @"');</script>";
            str += @"<script type='text/javascript'>window.history.go(-1);</script>";
            HttpContext.Current.Response.Write(str);
            HttpContext.Current.Response.End();
        }
        #endregion

        #region MessageBox用来在客户端弹出对话框，关闭对话框返回指定页。刷新上一级页面。
        /// <summary>
        /// 说明：MessageBox用来在客户端弹出对话框，关闭对话框返回指定页。
        /// 参数：TxtMessage 对话框中显示的内容。
        /// 参数：Url 对话框关闭后，跳转的页
        /// </summary>
        public static void MessageBox(string TxtMessage, string Url)
        {
            string str;
            if (Url == "")
            {
                str = "<script language=javascript>alert('" + TxtMessage + "');</script>";
            }
            else
            {
                str = "<script language=javascript>alert('" + TxtMessage + "');self.window.location='" + Url + "';</script>";
            }
            HttpContext.Current.Response.Write(str);
        }
        #endregion

        #region 字符串截取函数
        /// <summary>
        /// 字符串截取函数
        /// </summary>
        /// <param name="inputString">要截取的字符串</param>
        /// <param name="len">要截取的长度</param>
        /// <returns>string</returns>
        /// 
        public static string CutString(string inputString, int len)
        {
            //ASCIIEncoding ascii = new ASCIIEncoding();
            //int tempLen = 0;
            //string tempString = "";
            //byte[] s = ascii.GetBytes(inputString);
            //for (int i = 0; i < s.Length; i++)
            //{
            //    if ((int)s[i] == 63)
            //    {
            //        tempLen += 2;
            //    }
            //    else
            //    {
            //        tempLen += 1;
            //    }

            //    try
            //    {
            //        tempString += inputString.Substring(i, 1);
            //    }
            //    catch
            //    {
            //        break;
            //    }

            //    if (tempLen > len)
            //        break;
            //}
            ////如果截过则加上半个省略号 
            //byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
            //if (mybyte.Length > len)
            //    tempString += "..";
            //return tempString;
            return bSubstring(inputString, len, "..");
        }

        /// <summary>
        /// 是否中文
        /// </summary>
        /// <param name="chars"></param>
        /// <param name="RegType">true:包含中文;false:全部为中文</param>
        /// <returns></returns>
        public static bool IsChinese(string chars, bool RegType)
        {
            if (RegType)
            {
                return Regex.IsMatch(chars, @"^([\u4e00-\u9fa5]|[\uff01-\uff60]|\u3000){1,}$");
            }
            return Regex.IsMatch(chars, @"([\u4e00-\u9fa5]|[\uff01-\uff60]|\u3000){1,}");
        }

        /// <summary>
        /// 字符串截取（按字节）
        /// </summary>
        /// <param name="s"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string bSubstring(string s, int length)
        {
            string str = "";
            if (Encoding.GetEncoding("GB2312").GetBytes(s).Length < length)
            {
                return s;
            }
            if (!IsChinese(s, false))
            {
                return s.Substring(0, length);
            }
            if (IsChinese(s, true))
            {
                return s.Substring(0, length / 2);
            }
            int num = length / 2;
            int num2 = length;
            while (true)
            {
                str = str + s.Substring(str.Length, num);
                num2 = length - Encoding.GetEncoding("GB2312").GetBytes(str).Length;
                if (num2 <= 1)
                {
                    if ((num2 == 1) && (Encoding.GetEncoding("GB2312").GetBytes(s.Substring(str.Length, 1)).Length == 1))
                    {
                        str = str + s.Substring(str.Length, 1);
                    }
                    return str;
                }
                num = num2 / 2;
            }
        }
        /// <summary>  
        /// 求字符串的实际长度（汉字2个字节，外语字符1个字节）  
        /// </summary>  
        /// <param name="str"></param>  
        /// <returns></returns>  
        public static int Length(string str)
        {
            int len = 0;
            char[] arr = str.ToCharArray();
            for (int i = 0; i < arr.Length; i++)
            {
                //汉字  
                if (Asc(arr[i].ToString()) == -1)
                    len += 2;
                else
                    len += 1;
            }

            return len;
        }

        /// <summary>  
        /// 重写截取字符串方法，这里的长度是字节数（汉字2个字节，外语字符1个字节）  
        /// </summary>  
        /// <param name="str"></param>  
        /// <param name="length">截取长度（这里的长度是字节数，汉字2个字节，外语字符1个字节）</param>  
        /// <returns></returns>  
        public string Substring(string str, int length)
        {
            int len = 0;
            char[] arr = str.ToCharArray();
            string strReturn = string.Empty;

            //参数检查  
            if (length > Length(str))
                length = Length(str);


            for (int i = 0; i < arr.Length; i++)
            {
                //汉字  
                if (Asc(arr[i].ToString()) == -1)
                    len += 2;
                else
                    len += 1;

                if (len > length)
                    break;

                strReturn += arr[i].ToString();
            }

            return strReturn;
        }

        /// <summary>  
        /// 字符转ASCII码，如果未能转换为ASCII码返回-1  
        /// </summary>  
        /// <param name="character"></param>  
        /// <returns></returns>  
        public static int Asc(string character)
        {
            if (character.Length == 1)
            {
                //因为汉字和?都被转换为63，所以?进行提前处理  
                if (character == "?")
                    return 63;

                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0];

                //如果未能转换为ASCII码（暂且认为为汉字）  
                if (intAsciiCode == 63)
                    return -1;

                return (intAsciiCode);
            }
            else
            {
                throw new Exception("Character is not valid.");
            }
        }

        /// <summary>  
        /// ASCII码转字符  
        /// </summary>  
        /// <param name="asciiCode"></param>  
        /// <returns></returns>  
        public static string Chr(int asciiCode)
        {
            if (asciiCode >= 0 && asciiCode <= 255)
            {
                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                byte[] byteArray = new byte[] { (byte)asciiCode };
                string strCharacter = asciiEncoding.GetString(byteArray);
                return (strCharacter);
            }
            else
            {
                throw new Exception("ASCII Code is not valid.");
            }
        }

        /// <summary>
        /// 截取指定长度的字节数，并在末尾加上指定字符，比如 “...”
        /// </summary>
        /// <param name="s"></param>
        /// <param name="length"></param>
        /// <param name="p_TailString"></param>
        /// <returns></returns>
        public static string bSubstring(string s, int length, string p_TailString)
        {
            string str = bSubstring(s, length);
            if (Length(s)> length)
            //if (Encoding.GetEncoding("GB2312").GetBytes(s).Length > length)
            {
                str = str + p_TailString;
            }
            return str;
        }

        #endregion

        #region 删除所有缓存资源
        /// <summary>
        /// 删除所有缓存资源
        /// </summary>
        public static void RemoveAllCache()
        {
            Cache _cache = HttpRuntime.Cache;
            IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
            ArrayList _aList = new ArrayList();
            while (CacheEnum.MoveNext())
            {
                _aList.Add(CacheEnum.Key);
            }
            foreach (string tempcache in _aList)
            {
                _cache.Remove(tempcache);
            }
        }
        #endregion

        #region 格式化文本（防止SQL注入）
        /// <summary>
        /// 格式化文本（防止SQL注入）
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string MyFormatstr(string html)
        {
            System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            //System.Text.RegularExpressions.Regex regex6 = new System.Text.RegularExpressions.Regex(@"\<img[^\>]+\>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            //System.Text.RegularExpressions.Regex regex7 = new System.Text.RegularExpressions.Regex(@"</p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            //System.Text.RegularExpressions.Regex regex8 = new System.Text.RegularExpressions.Regex(@"<p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            //System.Text.RegularExpressions.Regex regex9 = new System.Text.RegularExpressions.Regex(@"<[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex10 = new System.Text.RegularExpressions.Regex(@"select", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex11 = new System.Text.RegularExpressions.Regex(@"update", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex12 = new System.Text.RegularExpressions.Regex(@"delete", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            html = regex1.Replace(html, ""); //过滤<script></script>标记
            html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
            html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
            html = regex4.Replace(html, ""); //过滤iframe
            html = regex5.Replace(html, ""); //过滤frameset
            //html = regex6.Replace(html, ""); //过滤frameset
            //html = regex7.Replace(html, ""); //过滤frameset
            //html = regex8.Replace(html, ""); //过滤frameset
            //html = regex9.Replace(html, "");
            html = regex10.Replace(html, "s_elect");
            html = regex11.Replace(html, "u_pudate");
            html = regex12.Replace(html, "d_elete");
            html = html.Replace("'", "’");
            html = html.Replace("&nbsp;", " ");
            //html = html.Replace("</strong>", "");
            //html = html.Replace("<strong>", "");
            return html;
        }
        #endregion

        #region 删除文件
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="argFilename">路径及文件名</param>
        /// <returns>操作结果.(成功/失败)</returns>
        public static bool DeleteFile(string argFilename)
        {
            if (File.Exists(argFilename) == true)
            {
                File.Delete(argFilename);
                return true;
            }
            return false;
        }
        #endregion

        #region 关闭当前窗口并且返回值
        /// <summary>
        /// 关闭当前窗口并且返回值
        /// </summary>
        public static void CloseWindowReturnValues(string value)
        {
            #region

            StringBuilder Str = new StringBuilder();
            Str.Append("<Script language='JavaScript'type=\"text/javascript\">");
            Str.Append("var str='" + value + "';");
            Str.Append("top.returnValue=str;");
            Str.Append("top.close();</Script>");

            HttpContext.Current.Response.Write(Str.ToString());
            HttpContext.Current.Response.End();
            #endregion
        }
        #endregion

        #region 获取QueryString中的值.并转化为int型
        /// <summary>
        /// 获取QueryString中的值.并转化为int型
        /// </summary>
        /// <param name="name">名</param>
        /// <param name="defaultValue">默认值, 数据转化错误时的返回值</param>
        /// <returns>结果</returns>
        public static int GetInt(string name, int defaultValue)
        {
            string queryStringValue = String.Empty;
            queryStringValue = HttpContext.Current.Request.QueryString[name];
            try
            {
                return int.Parse(queryStringValue);
            }
            catch { }
            return defaultValue;
        }
        #endregion
    }
}
